package StudyCode.summary.csv;

import java.util.Arrays;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class CreatesRowCSV {
	public static final String CR = "\r";
	public static final String LF = "\n";
	public static final String QUOTE = "\"";

	public static void main(String[] args) {
		String[] strings = new String[3];
		strings[0] = "www";
		strings[1] = "tah1986";
		strings[2] = "com";
		System.out.println("String 数组:" + Arrays.toString(strings));
		System.out.println("转为CSV行");
		System.out.println(makeCSVRow(strings, "-", true));
	}

	public static String makeCSVRow(String[] values, String sep,
	                                boolean addCR) {
		StringBuffer buf = new StringBuffer(values.length * 10);
		for (int i = 0; i < values.length; i++) {
			if (i > 0) {
				buf.append(sep);
			}

			String value = quoteCSVValue(values[i], sep);
			if (value != null) {
				buf.append(value);
			}
		}
		if (addCR) {
			buf.append(CR);
		}
		buf.append(LF);
		return buf.toString();
	}

	public static String quoteCSVValue(String value, String sep) {
		if (value == null) {
			return null;
		} else if (value.length() == 0) {
			return QUOTE + QUOTE;
		}

		value = value.replaceAll(QUOTE, QUOTE + QUOTE);

		boolean needQuote = false;
		needQuote = (value.indexOf(sep) != -1)
				|| (value.indexOf(QUOTE) != -1)
				|| (value.indexOf('\n') != -1)
				|| value.startsWith(" ") || value.endsWith(" ")
				|| value.startsWith("\t") || value.endsWith("\t");
		if (needQuote) {
			value = QUOTE + value + QUOTE;
		}

		return value;
	}
}
